

import org.xml.sax.SAXException;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

public class SAXParserHandler extends DefaultHandler{
	
	private String value=null;
	
	Literature record=null;
	
	private BufferedWriter bw;

	/*qName栈*/
	private Stack<String> stack=new Stack<String>();
	
	/*记录标识符*/
    private static int id=0;
	
	/*写入文件路径*/
	private String path="";

    /*写入文件路径--author*/
    private String path1="data/author.txt";
    
    /*写入文件路径--year和title*/
    private String path2="data/yeartitle.txt";

	/*标记变量 */
	private static int count=0;


	/*写入文件方法——写入作者*/
	public void docWriter(String path,List<String> author){	
		try{
			File infile=new File(path);
			bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(infile,true),"utf-8"));
			Iterator<String> it=author.iterator();
			while(it.hasNext()) {
				bw.write(it.next()+"#");
			    bw.flush();
			}
			bw.write("\n");//单独写入author文件时采用
			//bw.write("|");
			bw.flush();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			try{
				bw.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
	
	/*写入文件方法——写入其他属性*/
	public void docWriter(String path,String att){	
		try{
			File infile=new File(path);
			bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(infile,true),"utf-8"));
			bw.write(att+"\n");
			//bw.write(att+"|");
			bw.flush();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			try{
				bw.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
    /**写入文件方法-两个属性**/
    public void docWriter(String path,String att1,String att2) {
		try {
			File infile=new File(path);
			bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(infile,true),"utf-8"));
			bw.write(att1+"\n");
			bw.write(att2+"\n");
			bw.flush();
		}catch(IOException e) {
			e.printStackTrace();
		}finally {
			try {
				bw.close();
			}catch(IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**写入换行符 */
    public void docWriter(String path){
		try{
			File infile=new File(path);
			bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(infile,true),"utf-8"));
			bw.write('\n');
			bw.flush();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			try{
				bw.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}

	/**
	 * 重载读取文档的方法，显示开始读取的时间
	 */
    @Override
	public void startDocument() throws SAXException{
		super.startDocument();
		System.out.println("-----SCAN START!-----");
		SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date date = new Date(System.currentTimeMillis());
        System.out.println(formatter.format(date));
	}
	/**
	 * 重载读取元素的方法
	 * 并且给每一篇文章分配一个唯一的id用于创建索引
	 */
	@Override
	public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException{
		super.startElement(uri, localName, qName, attributes);
		stack.push(qName);
		if("article".equals(stack.peek())) {
			record=new Literature();
			record.setKey(attributes.getValue("key"));
			record.setId(id);
			/*if(record.getId()%10000==0){
				path="./data/paging/page_"+count+".txt";
				count++;
			}*/
			id++;
			docWriter(path1,Integer.toString(record.getId()));//写入author文件时采用
		}
	}
	/**
	 * 重载读取包含字符串的方法，写入字符串到记录文件
	 */
	@Override
	public void characters(char[] ch,int start,int length) throws SAXException {
		super.characters(ch, start, length);
		value=new String(ch,start,length);
		if("title".equals(stack.peek())) {
			record.setTitle(value);
		}else if("author".equals(stack.peek())){
			record.setAuthor(value);
		}else if("journal".equals(stack.peek())){
			record.setJournal(value);
		}else if("volume".equals(stack.peek())){
			record.setVolume(value);
		}else if("year".equals(stack.peek())){
			record.setYear(value);
		}else if("month".equals(stack.peek())){
			record.setMonth(value);
		}else if("cdrom".equals(stack.peek())){
			record.setCdrom(value);
		}else if("ee".equals(stack.peek())){
			record.setEe(value);
		}
		value=null;
	}
	/**
	 * 重载结束读取元素的方法
	 */
	@Override
	public void endElement(String uri,String localName,String qName) throws SAXException {
		super.endElement(uri, localName, qName);
		if("article".equals(stack.peek())) {
			/*docWriter(path,record.getTitle());
			docWriter(path, record.getAuthor());
			docWriter(path,record.getJournal());
			docWriter(path, record.getVolume());
			docWriter(path,record.getYear());
			docWriter(path,record.getMonth());
			docWriter(path,record.getCdrom());
			docWriter(path,record.getEe());
			docWriter(path);
			*/
            docWriter(path1,record.getAuthor());//写入author
            docWriter(path2,record.getYear(),record.getTitle());//写入year和titile
			//回收Literature对象
			//record=null;
			
		}
		//把标签弹出
		stack.pop();
	}
	/**
	 * 重载结束读取文档的方法，并显示结束读取的时间
	 */
	@Override
	public void endDocument() throws SAXException{
		super.endDocument();
		System.out.println("-----SACN ACCOMPLISH!-----");
		SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date date = new Date(System.currentTimeMillis());
        System.out.println(formatter.format(date));
	}
}